<template>
  <lay-container fluid="true" class="user-box">
    <!-- search -->
    <lay-card>
      <lay-form style="margin-top: 10px">
        <lay-row>
          <lay-col :md="5">
            <lay-form-item>
              <lay-tree-select v-model="searchQueryPage.unitId" :data="unitsData" @change="toSearch"
                size="sm" placeholder="请选择" :allow-clear="true" :replaceFields="replaceUnitFields"></lay-tree-select>
            </lay-form-item>
          </lay-col>
          <lay-col :md="4">
            <lay-form-item>
              <lay-input v-model="searchQueryPage.username" placeholder="用户账号"
                size="sm" :allow-clear="true" ></lay-input>
            </lay-form-item>
          </lay-col>
          <lay-col :md="4">
            <lay-form-item label=" " label-width="10">
              <lay-input v-model="searchQueryPage.name" placeholder="用户名"
                size="sm" :allow-clear="true" ></lay-input>
            </lay-form-item>
          </lay-col>
          <lay-col :md="4">
            <lay-form-item label-width="20">
              <lay-button style="margin-left: 20px" type="normal" size="sm" @click="toSearch">
                查询
              </lay-button>
              <lay-button size="sm" @click="toReset"> 重置 </lay-button>
            </lay-form-item>
          </lay-col>
        </lay-row>
      </lay-form>
    </lay-card>
    <!-- table -->
    <div class="table-box">
      <lay-table id="userId" :page="searchQueryPage" :height="'100%'" :columns="columns" :loading="loading" :default-toolbar="true"
        :data-source="dataSource" v-model:selectedKeys="selectedKeys" @sortChange="sortChange" @change="toSearch">
        <template #nonLockSt="{ row }">
          <lay-switch :model-value="row.nonLock == 0" @change="changeNonLock($event, row)"></lay-switch>
        </template>
        <template #nonExpiredSt="{ row }">
          <lay-switch :model-value="row.nonExpired == 0" @change="changeNonExpired($event, row)"></lay-switch>
        </template>
        <template #nonExpiredCSt="{ row }">
          <lay-switch :model-value="row.nonExpiredC == 0" @change="changeNonExpiredC($event, row)"></lay-switch>
        </template>
        <template #isEnabledSt="{ row }">
          <lay-switch :model-value="row.isEnabled == 1" @change="changeIsEnabled($event, row)"></lay-switch>
        </template>
        
        <template #roleName="{ row }">
          <lay-button size="sm" >{{row.roleName}}</lay-button>
        </template>
        <template v-slot:toolbar>
          <lay-button size="sm" type="primary" @click="changeVisibleUser('新增')">
            <lay-icon class="layui-icon-addition"></lay-icon>
            新增</lay-button>
          <lay-button size="sm" @click="toRemove">
            <lay-icon class="layui-icon-delete"></lay-icon>
            删除
          </lay-button>
        </template>
        <template v-slot:operator="{ row }">
          <lay-button size="xs" type="primary" @click="changeVisibleUser('编辑', row)" v-if="searchQueryPage.unitId == 1">编辑</lay-button>
          <lay-popconfirm content="确定要继续操作吗?" @confirm="toOneRemove(row.userId)" @cancel="cancel">
            <lay-button size="xs" border="red" border-style="dashed">{{searchQueryPage.unitId == 1? '删除' : '解除分配' }}</lay-button>
          </lay-popconfirm>
        </template>
      </lay-table>
    </div>
    <!-- saveOrUpdate -->
    <lay-layer v-model="visibleUser" :title="title" :area="['700px', '510px']">
      <div style="padding: 20px">
        <lay-form :model="formData" ref="formRef">
          
          <lay-form-item label="姓名" prop="name" required>
            <lay-input v-model="formData.name"></lay-input>
          </lay-form-item>
          <lay-form-item label="账户号" prop="username" required>
            <lay-input v-model="formData.username"></lay-input>
          </lay-form-item>
          <lay-form-item label="新密码" prop="password_new">
            <lay-input v-model="formData.password_new"></lay-input>
          </lay-form-item>
          
          <lay-form-item label="描述" prop="memo">
            <lay-textarea placeholder="请输入描述" v-model="formData.memo"></lay-textarea>
          </lay-form-item>
        </lay-form>
        <div style="width: 100%; text-align: center">
          <lay-button size="sm" type="primary" @click="toSubmit">保存</lay-button>
          <lay-button size="sm" @click="toCancel">取消</lay-button>
        </div>
      </div>
    </lay-layer>
    
  </lay-container>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import { layer } from '@layui/layui-vue'
  
  import { userList, userAdd, userRemove, userUnitList, unitTree } from '../../../api/module/system'
  
  // 其他
  // -- 加载中
  const loading = ref(false);
  const title = ref('新增')
  // 用户
  // -- 是否可见
  const visibleUser = ref(false)
  // -- 查询
  const searchQueryPage = ref({ username: '', name: '', unitId: 1, page: 1, size: 10, total: 0, orderProperty: '', orderSort: 0 });
  // -- 选中的
  const selectedKeys = ref([]);
  // -- 数据源
  const dataSource = ref([]);
  const unitsData = ref([]);
  // -- 树节点结构
  const replaceUnitFields = ref({ id: 'unitId', title: 'unitName', children: 'children' });
  // -- 表结构
  const columns = ref([
    { title: "复选", type: "checkbox" },
    
    { title: '账户号', key: 'username', sort: 'desc' },
    { title: '账户密码', key: 'password', hide: true },
    { title: '账户名', key: 'name', sort: 'desc' },
    
    { title: '描述', width: '280px', key: 'memo' },
    
    { title: '锁定', key: 'nonLock', customSlot: 'nonLockSt' },
    { title: '过期', key: 'nonExpired', customSlot: 'nonExpiredSt' },
    { title: '凭证过期', key: 'nonExpiredC', customSlot: 'nonExpiredCSt' },
    { title: '启用', key: 'isEnabled', customSlot: 'isEnabledSt' },
    
    { title: '角色', key: 'roleName', customSlot: 'roleName' }, 
    { title: '创建人编号', key: 'creatorId', hide: true },
    { title: '创建人', width: '80px', key: 'creatorName' },
    { title: '操作', width: '140px', customSlot: 'operator', key: 'operator', fixed: 'right' }
  ]);
  
  // 表单
  // -- 表单数据
  const formData = ref<any>({});
  // -- 表单标签
  const formRef = ref();
  
  // -- 方法函数
  // 加载默认数据
  function loadDataSource(){
    userList(searchQueryPage.value).then(({ data, code, msg }) => {
      if (code == 200) {
        searchQueryPage.value.total = data.total;
        dataSource.value = data.list;
      }
      loading.value = false;
    })
  }
  function loadUnitSource(){
    unitTree().then(({ data, code, msg }) => {
      if (code == 200) {
        unitsData.value = data;
      }
    })
  }
   // 刷新
  function toReset(){
    searchQueryPage.value.username = '';
    searchQueryPage.value.name = '';
  }
  // 搜索
  function toSearch() {
    searchQueryPage.value.page = 1
    loadDataSource()
  }
  // 搜索 sort
  function sortChange(key : any, sort : number){
    searchQueryPage.value.orderProperty = key;
    searchQueryPage.value.orderSort = sort;
  }
  // 删除
  function toRemove() {
    if (selectedKeys.value.length == 0) {
      layer.msg('您未选择数据，请先选择要删除的数据', { icon: 3, time: 2000 })
      return
    }
    layer.confirm('您将删除所有选中的数据？', {
      title: '提示',
      btn: [
        {
          text: '确定',
          callback: (id : any) => {
            userRemove({ids: selectedKeys.value, unitId: searchQueryPage.value.unitId}).then(({ code, msg }) => {
              if (code == 200) {
                layer.msg('成功删除！', { icon: 1, time: 1000 });
              } else {
                layer.msg(msg, { icon: 2, time: 1000 })
              }
              toSearch();
            })
            
            layer.close(id)
          }
        },
        {
          text: '取消',
          callback: (id : any) => {
            layer.msg('您已取消操作')
            layer.close(id)
          }
        }
      ]
    })
  }
  function toOneRemove(userId: number) {
    userRemove({ids: [userId], unitId: searchQueryPage.value.unitId}).then(({ code, msg }) => {
      if (code == 200) {
        layer.msg('成功删除！', { icon: 1, time: 1000 });
      } else {
        layer.msg(msg, { icon: 2, time: 1000 })
      }
      toSearch();
    })
  }
  // 提交
  function toSubmit() {
    userAdd(formData.value).then(({ data, code, msg, message }) => {
      if (code == 200) {
        layer.msg('保存成功！', { icon: 1, time: 1000 });
      } else {
        layer.msg(message? message:msg, { icon: 2, time: 1000 })
      }
      searchQueryPage.value.unitId = 1;
      toSearch();
      visibleUser.value = false
    })
  }
  // 
  function changeIsEnabled(isChecked : boolean, row : any){
    row.isEnabled = isChecked? 1 : 0;
    userAdd(row);
  }
  function changeNonLock(isChecked : boolean, row : any){
    row.nonLock = isChecked? 0 : 1;
    userAdd(row);
  }
  function changeNonExpired(isChecked : boolean, row : any){
    row.nonExpired = isChecked? 0 : 1;
    userAdd(row);
  }
  function changeNonExpiredC(isChecked : boolean, row : any){
    row.nonExpiredC = isChecked? 0 : 1;
    userAdd(row);
  }
  //
  function changeVisibleUser(text : any, row ?: any){
    title.value = text
    if (row) {
      let info = JSON.parse(JSON.stringify(row))
      formData.value = info
    } else {
      formData.value = {}
    }
    visibleUser.value = !visibleUser.value
  }
  //
  function toCancel(){
    visibleUser.value = false
  }
  function cancel(){
    layer.msg('您已取消操作')
  }
  
  // --预执行
  loadDataSource();
  loadUnitSource();
  
</script>

<style scoped>
  .user-box {
    height: calc(100vh - 110px); 
    margin-top: 10px; box-sizing: border-box; 
  } 
  
  .user-box .layui-tree-select{ width: auto; margin-right: 20px; }
  
  .top-search { margin-top: 10px; padding: 10px; height: 40px; border-radius: 4px; background-color: #fff; }
  
  .table-box { margin-top: 10px; padding: 10px; height: 730px; width: 100%; border-radius: 4px; box-sizing: border-box; background-color: #fff; } 
  
  .search-input { display: inline-block; width: 98%; margin-right: 10px; } 
  
  .isChecked { display: inline-block; background-color: #e8f1ff; color: red; }
</style>